from datetime import datetime, timezone
import importlib
from io import BytesIO
import json
import os
import subprocess
import random
import string
import uuid

import fitz
from oss_service.views import bucket
import requests
from dingtalk_service.yida_client_base import YidaClientBase
from yida_app_service.xu_cloud_client import XmCloudBaseClient

admin_user_id = '014835331124251186'

def get_yida_client(company_name):
    """
    根据提供的模块名称动态导入YidaClient类。

    :param company_name: 模块名称，比如 'zhongcheng' 或 'shujian'
    :return: 导入的YidaClient类
    """
    module_name = f'yida_app_service.{company_name}.yida_config'
    module = importlib.import_module(module_name)
    return getattr(module, 'YidaClient')

def get_xm_client(company_name):
    """
    根据提供的模块名称动态导入XmCloudClient类。

    :param company_name: 模块名称，比如 'zhongcheng' 或 'shujian'
    :return: 导入的XmCloudClient类
    """
    module_name = f'yida_app_service.{company_name}.xm_cloud_config'
    module = importlib.import_module(module_name)
    return getattr(module, 'XmCloudClient')
def attachment_to_xmfile(attachment,yida_client:YidaClientBase):
    xmfiles = []
    if isinstance(attachment,str):
        attachment = json.loads(attachment)
    for file in attachment:
        now_date = datetime.now(timezone.utc)
        oss_key = f"xm_cloud/detection_render_record/{now_date.strftime('%Y%m%d')}/{uuid.uuid4()}/{file['name']}"
        full_download_url = yida_client.get_full_download_url(
        user_id=admin_user_id, download_url=file["downloadURL"])
        url = full_download_url.body.result  # 从完整的下载链接响应中提取实际的文件下载链接。
        with requests.Session() as session:  # 使用 requests 库创建一个会话对象，用于发送 HTTP 请求。
            response = session.get(url)  # 发送 GET 请求以获取文件内容。
            if response.status_code == 200:
                file_content = response.content
                bucket.put_object(oss_key,file_content)
                xmfile = {
                    "uid": f"rc-upload-{file['lastModified']}-{file['name'].split('.')[0]}",
                    "url": oss_key,
                    "xhr": {},
                    "name": file["name"],
                    "size": file["size"],
                    "type": file["type"],
                    "status": "done",
                    "suffix": file["name"].split('.')[-1],
                    "percent": file["percent"],
                    "response": "",
                    "thumbUrl": "",
                    "lastModified": file["lastModified"],
                    "lastModifiedDate": file["lastModifiedDate"]
                }
                xmfiles.append(xmfile)
    if(len(xmfiles) == len(attachment)):
        return xmfiles
    else:
        raise ValueError("模版下载失败")

def xmfile_to_file(file):
    pass


def convert_to_pdf(input_file_path, output_dir):
    print("正在生成pdf")
    # LibreOffice 命令行
    #C:\\Program Files\\LibreOffice\\program\\soffice.exe
    cmd = [
        os.environ.get("SOFFICE_PATH","soffice"),
        "--headless",
        "--convert-to",
        "pdf",
        "--outdir",
        output_dir,
        input_file_path
    ]
    subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    return 



def generate_random_string(length):
    # 生成一个由数字和字母组成的字符集
    characters = string.ascii_letters + string.digits
    # 随机选择字符集中的字符，形成指定长度的字符串
    random_string = ''.join(random.choice(characters) for i in range(length))
    return random_string


def xm_fake_sign(company_name,form_uuid,pdf_key,form_inst_id,model_id):
    '''伪签署'''
    YidaClient = get_yida_client(company_name)
    yida_client:YidaClientBase = YidaClient()
    result = yida_client.get_form_items_by_ids(form_uuid,form_inst_id,yida_client.admin_user_id)
    if result:
        form_data = result[0].form_data
        pdf_instance = form_data.get(pdf_key)
        atta = json.loads(pdf_instance)[0]
        pdf_url = atta.get("downloadUrl")
        if not (pdf_url.startswith("https://api.zjxmyq.cn") or pdf_url.startswith("https://doc.zjxmyq.cn") or pdf_url.startswith("https://api.zjcxjc.cn") or pdf_url.startswith("https://doc.zjcxjc.cn")):
            res = yida_client.get_full_download_url(yida_client.admin_user_id,pdf_url)
            pdf_url = res.body.result
        XmCloudClient = get_xm_client(company_name)
        xm_client:XmCloudBaseClient = XmCloudClient()
        result = xm_client.get_model_info(model_id=model_id)  
        if result.get("code") == 200:
            model_info = result.get("data")
            sign_area = model_info.get("sign_area")
            if sign_area:
                response = requests.get(pdf_url)
                if response.status_code == 200:
                    pdf_content = BytesIO(response.content)
                    pdf_document = fitz.open(stream=pdf_content, filetype="pdf")
                    for sign_item in sign_area:
                        seal_key = sign_item.get("name")
                        page_num = sign_item.get("page")
                        seal_url = form_data.get(seal_key)
                        if not seal_url:
                            continue
                        img_res = requests.get(seal_url)
                        if response.status_code == 200:
                            cm_to_points = 28.35
                            img_content = BytesIO(img_res.content)
                            image_pix = fitz.Pixmap(img_content.getvalue())
                            page = pdf_document[page_num - 1]
                            page_height = page.rect.height
                            lbx = sign_item.get("x_axis") * cm_to_points  # 将 x 轴转换为 points
                            lby = sign_item.get("y_axis") * cm_to_points  # 将 y 轴转换为 points
                            size = sign_item.get("size") * cm_to_points  # 将尺寸转换为 points
                            rtx = lbx + size  # 右上角 x 坐标
                            rty = lby + size  # 右上角 y 坐标
                            # 由于 PDF 的坐标原点在左下角，需将 y 轴方向进行翻转
                            lby = page_height - lby
                            rty = page_height - rty
                            page.insert_image(fitz.Rect(lbx, rty, rtx, lby), pixmap=image_pix)
                    output_pdf_io = BytesIO()
                    pdf_document.save(output_pdf_io)
                    pdf_document.close()
                    output_pdf_io.seek(0)
                    object_key = f"{company_name}/{form_inst_id}/output_with_seals.pdf"
                    bucket.put_object(object_key,output_pdf_io)
                    yida_url = f"https://api.zjcxjc.cn/api/v1/yida-app/common/download_file/{object_key}"
                    yida_client.update_form_data_by_id(form_uuid, yida_client.admin_user_id, form_inst_id, {
                            pdf_key: [{
                                "downloadUrl": yida_url,
                                "name": atta.get("name"),
                                "previewUrl": yida_url,
                                "url": yida_url,
                                "ext": "pdf"
                            }]
                        })
                    print("签署文件更新成功")
    